package com.dayu.finecomm.dsc;

import io.netty.channel.ChannelInitializer;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dayu.finecomm.dsc.net.DSCNetManager;

/**
 * DSC相关对外接口
 * 
 * @author hddz
 * @since 2017-07-31 15:49:00
 * @version V1.0
 */
public class DSC {
	static Logger LOGGER = LoggerFactory.getLogger(DSC.class);

	/**
	 * 单例模式
	 */
	private volatile static DSC mSelf = null;

	/**
	 * DSC服务状态: 0 - stop, 1 - working
	 */
	private volatile int mDSCStatus;

	/**
	 * 创建DSC单例
	 * 
	 * @return DSC
	 */
	public static DSC getInstance() {
		if (null == mSelf) {
			synchronized (DSC.class) {
				if (null == mSelf) {
					mSelf = new DSC();
				}
			}
		}

		return mSelf;
	}

	private DSC() {
		mDSCStatus = 0;
	}

	/**
	 * 启动DSC服务
	 * 
	 * @param nType
	 *            开启socket类型， 1 - TCP, 2 - UDP
	 * @param nPort
	 *            端口号
	 * @param channel
	 *            事件处理Handler
	 * @return 0 - success, -1 - failed
	 */
	public int startDscServer(int nType, String host, int nPort,
			ChannelInitializer<?> channel) {
		int nResult = -1;

		if (0 == mDSCStatus) {
			DSCNetManager.getInstance().init();
			DTUProxyManager.getInstance().init();

			DSCInterface dscInterface = new DSCInterface(channel);

			nResult = DSCNetManager.getInstance().createSocket(nType, host,
					nPort, dscInterface);

			mDSCStatus = 1;
		}

		return nResult;
	}

	/**
	 * 停止DSC服务
	 */
	public void stopDscServer() {
		if (1 == mDSCStatus) {
			DTUProxyManager.getInstance().uninit();
			DSCNetManager.getInstance().uninit();
			mDSCStatus = 0;
		}
	}

	/**
	 * 获取所有DTU设备的数量
	 * 
	 * @return
	 */
	public int getTotalDTU() {
		return DTUProxyManager.getInstance().getTotalDTU();
	}

	/**
	 * 获取所有DTU设备的Identify
	 * 
	 * @return List<String>
	 */
	public List<String> getTotalDtuIdentify() {
		return DTUProxyManager.getInstance().getTotalDtuIdentify();
	}

	/**
	 * 通过索引，获取Identify
	 * 
	 * @param index
	 * @return Identify
	 */
	public String getDtuIdentify(int index) {
		return DTUProxyManager.getInstance().getDtuIdentify(index);
	}

	/**
	 * 发送用户数据到DTU
	 * 
	 * @param identify
	 *            DTU identify
	 * @param msg
	 * @return 0 - success, -1 - failed
	 */
	public int sendDataToDTU(String identify, byte[] msg) {
		return DTUProxyManager.getInstance().sendDataToDTU(identify, msg);
	}
}
